package org.jhh.domain.activity.service.armory;

import org.jhh.domain.activity.model.entity.ActivitySkuEntity;
import org.jhh.domain.activity.repository.IActivityRepository;
import org.jhh.types.common.Constants;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ActivityArmory implements IActivityArmory,IActivityDispatch {

    @Resource
    private IActivityRepository activityRepository;

    @Override
    public boolean assembleActivitySku(Long sku) {
//预热 商品库存 - 活动信息 - 活动次数
        ActivitySkuEntity activitySkuEntity = activityRepository.queryActivitySku(sku);
        //        预热活动sku库存
        cacheActivitySkuStockCount(sku,activitySkuEntity.getStockCount());
//        预热活动 【查询时预热到缓存】
        activityRepository.queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());
//        预热活动次数
        activityRepository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());

        return true;
    }

    private void cacheActivitySkuStockCount(Long sku, Integer stockCount) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        activityRepository.cacheActivitySkuStockCount(cacheKey, stockCount);
    }

    @Override
    public boolean subtractionActivitySkuStock(Long sku, Date endDateTime) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        return activityRepository.subtractionActivitySkuStock(sku,cacheKey,endDateTime);
    }

    @Override
    public boolean assembleActivitySkuByActivityId(Long activityId) {
//      装配商品活动通过活动ID
        List<ActivitySkuEntity> activitySkuEntities = activityRepository.queryActivitySkuListByActivityId(activityId);
        for(ActivitySkuEntity activitySkuEntity : activitySkuEntities){
            cacheActivitySkuStockCount(activitySkuEntity.getSku(),activitySkuEntity.getStockCountSurplus());
//            预热活动次数 【查询时预热到缓存】
            activityRepository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        }
//              预热活动【查询时预热到缓存】
            activityRepository.queryRaffleActivityByActivityId(activityId);

            return true;
    }
}
